package zhttp

import (
    "context"
    "fmt"
    "net/http"
    "sync"

    "gitee.com/shijingzhao/z-frame/zlog"
)

// Config http服务器配置
type Config struct {
    Addr string `json:"addr"`
}

type Http struct {
    ctx context.Context

    config Config
    router *Router

    server *http.Server
}

// NewHttp 实例http服务器
func NewHttp(ctx context.Context, config Config) *Http {
    h := &Http{
        ctx:    ctx,
        config: config,
        router: &Router{},
    }
    return h
}

// Start 启动
func (h *Http) Start(wg *sync.WaitGroup) {
    wg.Add(1)

    go func() {
        defer wg.Done()

        h.server = &http.Server{
            Addr:    h.config.Addr,
            Handler: h.router,
        }

        if err := h.server.ListenAndServe(); err != nil {
            if err != http.ErrServerClosed {
                panic(any(fmt.Sprintf("http服务器:启动失败[%s]", err.Error())))
            }
        }
    }()
}

// ShutDown 终止
func (h *Http) ShutDown() {
    err := h.server.Shutdown(context.Background())
    if err != nil {
        zlog.NewSystemLogger(context.TODO()).Error("http服务器:终止错误", zlog.String("err", err.Error()))
    }
    zlog.NewSystemLogger(context.TODO()).System("http服务器终止")
}
